import { View, Text, TouchableOpacity, FlatList, Image, StyleSheet, ActivityIndicator } from 'react-native';
import React, { useState, useEffect } from 'react';
import { Stack, useRouter } from 'expo-router';
import { useTheme } from '../context/ThemeContext';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { Tabs } from 'expo-router/tabs';
import { getFriendList, getPrivateHistory, FriendType, getGroupList, GroupType } from '../services/chatService';
import { format } from 'date-fns';

// 消息列表项类型定义
type MessageItem = {
  id: number;
  avatar: string;
  name: string;
  content: string;
  time: string;
  unread?: number;
};

export default function MessageScreen() {
  const { isDarkMode } = useTheme();
  const router = useRouter();
  const [activeTab, setActiveTab] = useState('private');
  const [privateMessages, setPrivateMessages] = useState<MessageItem[]>([]);
  const [groupMessages, setGroupMessages] = useState<MessageItem[]>([]);
  const [notifications, setNotifications] = useState<MessageItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  
  // 加载好友列表和最新消息
  useEffect(() => {
    const loadFriends = async () => {
      try {
        setLoading(true);
        setError(null);
        
        // 获取好友列表
        const friends = await getFriendList();
        
        // 转换为消息列表项
        const messageItems: MessageItem[] = await Promise.all(
          friends.map(async (friend) => {
            try {
              // 获取与每个好友的最新一条消息
              const chatHistory = await getPrivateHistory(friend.friendId, 1, 1);
              const latestMessage = chatHistory.records[0];
              
              return {
                id: friend.friendId,
                name: friend.remark || friend.userName,
                avatar: friend.userAvatar || 'https://via.placeholder.com/50',
                content: latestMessage 
                  ? latestMessage.content 
                  : '开始聊天吧',
                time: latestMessage 
                  ? formatTime(latestMessage.createTime)
                  : formatTime(friend.createTime),
                unread: chatHistory.records.filter(
                  msg => msg.status === 0 && msg.fromUserId === friend.friendId
                ).length
              };
            } catch (error) {
              console.error(`获取与好友 ${friend.friendId} 的聊天记录失败:`, error);
              // 如果获取聊天记录失败，返回基本信息
              return {
                id: friend.friendId,
                name: friend.remark || friend.userName,
                avatar: friend.userAvatar || 'https://via.placeholder.com/50',
                content: '点击开始聊天',
                time: formatTime(friend.createTime),
                unread: 0
              };
            }
          })
        );
        
        // 根据时间排序，最新的消息在前面
        messageItems.sort((a, b) => {
          // 将时间格式转换为可比较的格式
          const getTimeValue = (timeStr: string): number => {
            if (timeStr === '今天') return Date.now();
            if (timeStr === '昨天') return Date.now() - 86400000;
            if (timeStr === '前天') return Date.now() - 172800000;
            if (timeStr.includes('周')) return Date.now() - 604800000;
            // 对于日期格式，尝试转换为时间戳
            try {
              return new Date(timeStr).getTime();
            } catch (e) {
              return 0;
            }
          };
          
          return getTimeValue(b.time) - getTimeValue(a.time);
        });
        
        setPrivateMessages(messageItems);
      } catch (error) {
        console.error('加载好友列表失败:', error);
        setError('加载好友列表失败，请检查网络连接');
      } finally {
        setLoading(false);
      }
    };
    
    const loadGroups = async () => {
      try {
        // 获取群组列表
        const groups = await getGroupList();
        
        // 转换为消息列表项
        const messageItems: MessageItem[] = groups.map((group) => ({
          id: group.id,
          name: group.groupName,
          avatar: group.avatar || 'https://via.placeholder.com/50',
          content: `${group.memberCount}个成员`,
          time: formatTime(group.createTime),
          unread: 0 // 未读消息数需要单独API获取
        }));
        
        setGroupMessages(messageItems);
      } catch (error) {
        console.error('加载群组列表失败:', error);
      }
    };
    
    if (activeTab === 'private') {
      loadFriends();
    } else if (activeTab === 'group') {
      loadGroups();
    } else {
      // 加载通知（假数据，可根据实际API替换）
      setNotifications([
        {
          id: 201,
          name: '系统通知',
          avatar: 'https://via.placeholder.com/50',
          content: '您的账号已激活，欢迎使用校园聊天系统',
          time: '2023-05-01',
        },
      ]);
    }
  }, [activeTab]);
  
  // 格式化时间
  const formatTime = (timeStr: string) => {
    const date = new Date(timeStr);
    const now = new Date();
    
    if (date.toDateString() === now.toDateString()) {
      return '今天';
    } else if (date.getTime() > now.getTime() - 86400000) {
      return '昨天';
    } else if (date.getFullYear() === now.getFullYear()) {
      return format(date, 'MM-dd');
    } else {
      return format(date, 'yyyy-MM-dd');
    }
  };

  // 渲染消息项
  const renderMessageItem = ({ item }: { item: MessageItem }) => (
    <TouchableOpacity 
      style={[
        styles.messageItem,
        { backgroundColor: isDarkMode ? '#1A1A1A' : '#FFFFFF' }
      ]}
      onPress={() => handleMessagePress(item)}
    >
      <View style={styles.avatarContainer}>
        <Image 
          source={{ uri: item.avatar }} 
          style={styles.avatar}
        />
        {item.unread && item.unread > 0 && (
          <View style={styles.badge}>
            <Text style={styles.badgeText}>{item.unread}</Text>
          </View>
        )}
      </View>
      <View style={styles.messageContent}>
        <View style={styles.messageHeader}>
          <Text style={{ 
            fontWeight: 'bold', 
            fontSize: 16,
            color: isDarkMode ? '#FFFFFF' : '#000000'
          }}>
            {item.name}
          </Text>
          <Text style={{ 
            fontSize: 12, 
            color: isDarkMode ? '#999999' : '#666666' 
          }}>
            {item.time}
          </Text>
        </View>
        <Text 
          style={{ 
            color: isDarkMode ? '#CCCCCC' : '#333333',
            marginTop: 4
          }}
          numberOfLines={1}
        >
          {item.content}
        </Text>
      </View>
    </TouchableOpacity>
  );

  // 处理消息点击
  const handleMessagePress = (item: MessageItem) => {
    if (activeTab === 'private') {
      router.push(`/chat/private/${item.id}?name=${item.name}`);
    } else if (activeTab === 'group') {
      router.push(`/chat/group/${item.id}?name=${item.name}`);
    } else {
      // 通知的处理
      alert(`查看通知: ${item.content}`);
    }
  };
  
  // 渲染加载中状态
  const renderLoading = () => (
    <View style={styles.loadingContainer}>
      <ActivityIndicator size="large" color={isDarkMode ? '#3B82F6' : '#2563EB'} />
      <Text style={{ 
        color: isDarkMode ? '#BBBBBB' : '#666666',
        marginTop: 10
      }}>
        加载中...
      </Text>
    </View>
  );
  
  // 渲染错误状态
  const renderError = () => (
    <View style={styles.emptyContainer}>
      <Text style={{ 
        color: isDarkMode ? '#FF6B6B' : '#FF3B30',
        fontSize: 16,
        marginBottom: 10
      }}>
        {error}
      </Text>
      <TouchableOpacity
        style={styles.retryButton}
        onPress={() => setActiveTab(activeTab)} // 重新触发加载
      >
        <Text style={{ color: '#FFFFFF' }}>重试</Text>
      </TouchableOpacity>
    </View>
  );
  
  // 渲染空列表状态
  const renderEmpty = () => (
    <View style={styles.emptyContainer}>
      <Text style={{
        color: isDarkMode ? '#BBBBBB' : '#999999',
        fontSize: 16
      }}>
        {activeTab === 'private' 
          ? '暂无好友，去添加新好友吧' 
          : activeTab === 'group' 
            ? '暂无群聊，去创建或加入群组吧'
            : '暂无通知'}
      </Text>
      {(activeTab === 'private' || activeTab === 'group') && (
        <TouchableOpacity
          style={styles.addButton}
          onPress={handleAddPress}
        >
          <Text style={{ color: '#FFFFFF' }}>
            {activeTab === 'private' ? '添加好友' : '创建群组'}
          </Text>
        </TouchableOpacity>
      )}
    </View>
  );

  // 处理搜索按钮点击
  const handleSearchPress = () => {
    router.push('/search');
  };

  // 处理添加联系人按钮点击
  const handleAddPress = () => {
    if (activeTab === 'private') {
      router.push('/friend/add');
    } else if (activeTab === 'group') {
      router.push('/group/create');
    }
  };

  return (
    <>
      <Stack.Screen options={{ 
        title: '消息',
        headerStyle: {
          backgroundColor: isDarkMode ? '#1E1E1E' : '#FFFFFF',
        },
        headerTintColor: isDarkMode ? '#FFFFFF' : '#333333',
        headerRight: () => (
          <View style={{ flexDirection: 'row' }}>
            <TouchableOpacity onPress={handleSearchPress} style={{ marginRight: 15 }}>
              <MaterialCommunityIcons 
                name="magnify" 
                size={24} 
                color={isDarkMode ? '#FFFFFF' : '#333333'} 
              />
            </TouchableOpacity>
            <TouchableOpacity onPress={handleAddPress}>
              <MaterialCommunityIcons 
                name="account-plus" 
                size={24} 
                color={isDarkMode ? '#FFFFFF' : '#333333'} 
              />
            </TouchableOpacity>
          </View>
        ),
      }} />
      
      <View style={{ 
        flex: 1, 
        backgroundColor: isDarkMode ? '#121212' : '#F5F5F5'
      }}>
        {/* 选项卡 */}
        <View style={[
          styles.tabsContainer,
          { backgroundColor: isDarkMode ? '#1E1E1E' : '#FFFFFF' }
        ]}>
          <TouchableOpacity 
            style={[
              styles.tab, 
              activeTab === 'private' && styles.activeTab
            ]}
            onPress={() => setActiveTab('private')}
          >
            <Text style={[
              styles.tabText,
              activeTab === 'private' && styles.activeTabText,
              { color: isDarkMode ? (activeTab === 'private' ? '#3B82F6' : '#BBBBBB') : (activeTab === 'private' ? '#3B82F6' : '#666666') }
            ]}>
              私聊
            </Text>
          </TouchableOpacity>

          <TouchableOpacity 
            style={[
              styles.tab, 
              activeTab === 'group' && styles.activeTab
            ]}
            onPress={() => setActiveTab('group')}
          >
            <Text style={[
              styles.tabText,
              activeTab === 'group' && styles.activeTabText,
              { color: isDarkMode ? (activeTab === 'group' ? '#3B82F6' : '#BBBBBB') : (activeTab === 'group' ? '#3B82F6' : '#666666') }
            ]}>
              群聊
            </Text>
          </TouchableOpacity>

          <TouchableOpacity 
            style={[
              styles.tab, 
              activeTab === 'notification' && styles.activeTab
            ]}
            onPress={() => setActiveTab('notification')}
          >
            <Text style={[
              styles.tabText,
              activeTab === 'notification' && styles.activeTabText,
              { color: isDarkMode ? (activeTab === 'notification' ? '#3B82F6' : '#BBBBBB') : (activeTab === 'notification' ? '#3B82F6' : '#666666') }
            ]}>
              通知
            </Text>
          </TouchableOpacity>
        </View>

        {/* 消息列表 */}
        {activeTab === 'private' && (
          loading ? renderLoading() :
          error ? renderError() :
          <FlatList
            data={privateMessages}
            renderItem={renderMessageItem}
            keyExtractor={(item) => item.id.toString()}
            contentContainerStyle={{ paddingVertical: 8 }}
            ListEmptyComponent={renderEmpty()}
          />
        )}
        
        {activeTab === 'group' && (
          <FlatList
            data={groupMessages}
            renderItem={renderMessageItem}
            keyExtractor={(item) => item.id.toString()}
            contentContainerStyle={{ paddingVertical: 8 }}
            ListEmptyComponent={renderEmpty()}
          />
        )}
        
        {activeTab === 'notification' && (
          <FlatList
            data={notifications}
            renderItem={renderMessageItem}
            keyExtractor={(item) => item.id.toString()}
            contentContainerStyle={{ paddingVertical: 8 }}
            ListEmptyComponent={renderEmpty()}
          />
        )}
      </View>
    </>
  );
}

const styles = StyleSheet.create({
  tabsContainer: {
    flexDirection: 'row',
    borderBottomWidth: 1,
    borderBottomColor: '#EEEEEE',
    marginBottom: 5,
  },
  tab: {
    flex: 1,
    paddingVertical: 15,
    alignItems: 'center',
  },
  activeTab: {
    borderBottomWidth: 2,
    borderBottomColor: '#3B82F6',
  },
  tabText: {
    fontSize: 16,
  },
  activeTabText: {
    fontWeight: 'bold',
  },
  messageItem: {
    flexDirection: 'row',
    padding: 15,
    borderBottomWidth: 1,
    borderBottomColor: '#EEEEEE',
  },
  avatarContainer: {
    position: 'relative',
  },
  avatar: {
    width: 50,
    height: 50,
    borderRadius: 25,
  },
  badge: {
    position: 'absolute',
    top: 0,
    right: 0,
    backgroundColor: '#FF3B30',
    borderRadius: 10,
    width: 18,
    height: 18,
    justifyContent: 'center',
    alignItems: 'center',
  },
  badgeText: {
    color: 'white',
    fontSize: 10,
    fontWeight: 'bold',
  },
  messageContent: {
    flex: 1,
    marginLeft: 15,
    justifyContent: 'center',
  },
  messageHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  emptyContainer: {
    flex: 1,
    height: 300,
    justifyContent: 'center',
    alignItems: 'center',
  },
  retryButton: {
    backgroundColor: '#3B82F6',
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 20,
  },
  addButton: {
    backgroundColor: '#3B82F6',
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 20,
    marginTop: 15,
  }
}); 